package com.dongwu.manager.web;

import com.dongwu.common.dto.PagingVO;
import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.Exceptions;
import com.dongwu.common.web.BaseController;
import com.dongwu.common.web.Servlets;
import com.dongwu.manager.entity.UserInfo;
import com.dongwu.security.utils.SecurityUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/manager/userInfo")
public class UserInfoController extends BaseController<UserInfo, String> {

    @RequestMapping(value = "/queryPage")
    @ResponseBody
    public Result queryPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {
        try {
            if (!SecurityUtils.hasRole(this.getQueryRole())) {
                return Result.denyResult();
            }
            if (pageNo == null) {
                pageNo = 1;
            }
            if (pageSize == null) {
                pageSize = 10;
            }
            PageRequest PageRequest = new PageRequest(pageNo - 1, pageSize);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
            // 统一过滤数据权限
            filterDataPermission(searchParams);
            Page<UserInfo> page = baseService.findPage(PageRequest, searchParams);
            PagingVO paging = new PagingVO(page.getContent(),
                    (int)page.getTotalElements(), pageNo, pageSize);
            List<UserInfo> list = page.getContent();
            Base64.Decoder decoder = Base64.getDecoder();
            for(UserInfo userInfo : list){
                userInfo.setNickname(new String(decoder.decode(userInfo.getNickname()), "UTF-8"));
            }
            return Result.successResult(paging);
        } catch (Exception e) {
            String msg = Exceptions.getMessage(e);
            logger.error(msg, e);
            return Result.errorResult(msg);
        }
    }

}
